var app = getApp(),
  api = require("../../api.js"),
  QQMapWX = require("../../utils/qqmap-wx-jssdk.js"),
  images = require('../../utils/images.js');
var util = require("../../utils/utils");
var qqmapsdk;
Page({
  data: {
    userInfo: 0,
    page: 1,
    limit: 10,
    commentPage: 1,
    commentLimit: 5,
    last_count: 10,
    folkList: [],
    nowAddress: '湖南省长沙市天心区雀园路',
    collarStatus: 0,
    lineClamp: !0,
    btnText: '显示全文',
    btnShow: !1,
    news1: '这里的风景真好看这里的风景真好看这里的风景真好看这里的风景真好看这里的风景真好看这里的风景真好看',
    news2: '对呀！',
    content: '如果你无法简洁的表达你的想法，那只说明你还不够了解它；如果你无法简洁的表达你的想法，那只说明你还不够了解它；如果你无法简洁的表达你的想法，那只说明你还不够了解它； -- 阿尔伯特·爱因斯坦',
    changeIcon: images.nearbyShop.changeIcon,
    positionIcon: images.nearbyShop.positionIcon,
  },
  onLoad: function(n) {
    app.pageOnLoad(this)
    var that = this;
    var userInfo = wx.getStorageSync("user_info");
    this.setData({
      userInfo: userInfo
    });
    qqmapsdk = new QQMapWX({
      key: 'XALBZ-UOZCI-PHQG7-5CBUT-JH6HQ-GWFES'
    });
    wx.showLoading({
      title: "加载中"
    }), wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: function(res) {
              that.getMyLocation(that.getFolkList);
            },
            complete: function() {
              wx.hideLoading();
            }
          });
        } else {
          that.getMyLocation(that.getFolkList);
        }
      }
    });
    that.judgeHeight();
  },
  getFolkList: function() {
    var that = this;
    var data = {
      page: this.data.page,
      limit: this.data.limit,
      order_by: this.data.collarStatus,
      lng: this.data.lng,
      lat: this.data.lat
    };
    wx.showLoading({
      title: "加载中..."
    });
    app.request({
      url: api.folk.list,
      data: data,
      success: function(res) {
        if (res.code == 0) {
          that.setData({
            last_count: res.data.folks.length,
            page: that.data.page + 1
          });
          res.data.folks.forEach((item, index) => {
            console.log(item.addtime)
            item.time = util.formatTime(new Date(item.addtime * 1000));
            that.getComentListByID(item.id).then(data => {
              var tempObj = item;
              tempObj.comments = data.comments;
              if (data.comments.length == that.data.commentLimit) {
                tempObj.hasMore = true
              }
              that.setData({
                folkList: that.data.folkList.concat([tempObj])
              });
            });
          });
        }
      },
      fail: function(err) {
        wx.showToast({
          title: '获取主题列表失败',
          image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
        });
      },
      complete: function(d) {
        wx.hideLoading();
      }
    })
  },
  getComentListByID: function(folkID) {
    var data = {
      page: this.data.commentPage,
      limit: this.data.commentLimit,
      folks_id: folkID
    };
    wx.showLoading({
      title: "加载中..."
    });
    return new Promise((resolve, reject) => {
      app.request({
        url: api.folk.comments,
        data: data,
        success: function(res) {
          if (res.code == 0) {
            resolve(res.data);
          }
        },
        fail: function(err) {
          wx.showToast({
            title: '获取主题列表失败',
            image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
          });
        },
        complete: function(d) {
          wx.hideLoading();
        }
      });
    });
  },
  getMyLocation: function(callback) {
    var that = this;
    wx.getLocation({
      success: function(t) {
        (that.data.lng = t.longitude, that.data.lat = t.latitude) && that.setData({
          lng: that.data.lng,
          lat: that.data.lat
        });
        if (typeof callback == 'function') {
          callback();
        }
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: t.latitude,
            longitude: t.longitude
          },
          success: function(addressRes) {
            var address = addressRes.result.formatted_addresses.recommend;
            that.data.nowAddress = address, that.setData({
              nowAddress: that.data.nowAddress
            })
          },
          fail: function(res) {
            wx.showToast({
              title: '获取位置失败'
            });
          },
          complete: function() {
            wx.hideLoading();
          }
        });
      }
    });
  },
  chooseAddress: function(a) {
    var e = this;
    wx.getSetting({
      success: function(t) {
        t.authSetting["scope.userLocation"] ? e.location(a) : app.getauth({
          content: "需要获取您的地理位置授权，请到小程序设置中打开授权！",
          cancel: !1,
          success: function(t) {
            t.authSetting["scope.userLocation"] && e.location(a);
          }
        });
      }
    });
  },
  location: function(t) {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        (that.data.lng = res.longitude, that.data.lat = res.latitude, that.data.nowAddress = res.name) && that.setData({
          lng: that.data.lng,
          lat: that.data.lat,
          nowAddress: that.data.nowAddress
        });
      },
      fail: function(res) {
        wx.showToast({
          title: '选择位置失败'
        })
      }
    });
  },
  chooseStatus: function(e) {
    var that = this;
    var status = e.currentTarget.dataset.status;
    that.setData({
      page: 1,
      folkList: [],
      collarStatus: status
    });
    this.getFolkList();
  },
  changeArticle: function(e) {
    var that = this;
    if (that.data.lineClamp) {
      that.setData({
        lineClamp: !1,
        btnText: '隐藏显示'
      });
    } else {
      that.setData({
        lineClamp: !0,
        btnText: '全文显示'
      });
    }
  },
  judgeHeight: function(e) {
    var that = this;
    var query = wx.createSelectorQuery();
    // query.select('.article-cont').boundingClientRect()
    // query.exec(function (res) {
    //   //res就是 所有标签为mjltest的元素的信息 的数组
    //   if(res[0].height > 80){
    //     that.setData({
    //       btnShow: !0
    //     });
    //   }
    // })
  },
  previewImage: function(e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url] // 需要预览的图片http链接列表
    })
  },
  goPublish: function(e) {
    wx.navigateTo({
      url: '/pages/publish/publish',
    })
  },
  onReady: function() {},
  onShow: function() {},
  onHide: function() {},
  onUnload: function() {},
  onPullDownRefresh: function() {},
  onReachBottom: function() {
    if (this.data.last_count == this.data.limit) {
      this.getFolkList()
    }
  },
  onShareAppMessage: function() {},
  getMoreComments(e) {
    // /pages/folks/comments/comments?folk_item={{JSON.stringify(item)}}
    var folkItem = JSON.stringify(e.currentTarget.dataset.item);
    wx.navigateTo({
      url: '/pages/folks/comments/comments?folk_item=' + folkItem
    });
  },
  deleteItem: function(e) {
    var a = this;
    var folks_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "是否删除",
      cancelText: "否",
      confirmText: "是",
      success: function(t) {
        if (t.cancel) return !0;
        t.confirm && (wx.showLoading({
          title: "操作中"
        }), app.request({
          url: api.folk.delete,
          method: 'POST',
          data: {
            folks_id: folks_id
          },
          success: function(t) {
            wx.hideLoading(), wx.showModal({
              title: "提示",
              content: t.msg,
              showCancel: !1,
              success: function(t) {
                if (t.confirm) {
                  var list = a.data.folkList;
                  for (var i = 0; i < list.length; i++) {
                    if (list[i].id == folks_id) {
                      list.splice(i, 1);
                      break;
                    }
                  }

                  a.setData({
                    folkList: list
                  });
                }
              }
            });
          }
        }));
      }
    });
  },
});